package org.nyt.medicalstore.controller;

import org.nyt.medicalstore.model.SaleRecord;
import org.nyt.medicalstore.service.SaleRecordService;
import org.nyt.medicalstore.dto.SaleRecordDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/sale-records")
@CrossOrigin(origins = "*")
public class SaleRecordController {
    @Autowired
    private SaleRecordService saleRecordService;

    private SaleRecordDTO toDTO(SaleRecord saleRecord) {
        if (saleRecord == null) return null;
        SaleRecordDTO dto = new SaleRecordDTO();
        dto.setId(saleRecord.getId());
        dto.setDrugId(saleRecord.getDrug() != null ? saleRecord.getDrug().getId() : null);
        dto.setCustomerId(saleRecord.getCustomer() != null ? saleRecord.getCustomer().getId() : null);
        dto.setQuantity(saleRecord.getQuantity());
        dto.setUnitPrice(saleRecord.getUnitPrice());
        dto.setTotalAmount(saleRecord.getTotalAmount());
        dto.setSaleDate(saleRecord.getSaleDate());
        dto.setPrescriptionNumber(saleRecord.getPrescriptionNumber());
        return dto;
    }

    @GetMapping
    public ResponseEntity<?> getAllSaleRecords() {
        try {
            List<SaleRecord> saleRecords = saleRecordService.getAllSaleRecords();
            List<SaleRecordDTO> result = saleRecords.stream().map(this::toDTO).collect(Collectors.toList());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"获取销售记录失败: " + e.getMessage() + "\"}");
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getSaleRecord(@PathVariable Long id) {
        try {
            SaleRecord saleRecord = saleRecordService.getSaleRecordById(id);
            if (saleRecord == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("{\"error\": \"销售记录不存在\"}");
            }
            SaleRecordDTO result = toDTO(saleRecord);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"获取销售记录失败: " + e.getMessage() + "\"}");
        }
    }

    @PostMapping
    public ResponseEntity<?> addSaleRecord(@RequestBody SaleRecord saleRecord) {
        try {
            SaleRecord savedSaleRecord = saleRecordService.saveSaleRecord(saleRecord);
            SaleRecordDTO result = toDTO(savedSaleRecord);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"添加销售记录失败: " + e.getMessage() + "\"}");
        }
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updateSaleRecord(@PathVariable Long id, @RequestBody SaleRecord saleRecord) {
        try {
            SaleRecord existingSaleRecord = saleRecordService.getSaleRecordById(id);
            if (existingSaleRecord == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("{\"error\": \"销售记录不存在\"}");
            }
            saleRecord.setId(id);
            SaleRecord updatedSaleRecord = saleRecordService.saveSaleRecord(saleRecord);
            SaleRecordDTO result = toDTO(updatedSaleRecord);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"更新销售记录失败: " + e.getMessage() + "\"}");
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteSaleRecord(@PathVariable Long id) {
        try {
            SaleRecord existingSaleRecord = saleRecordService.getSaleRecordById(id);
            if (existingSaleRecord == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("{\"error\": \"销售记录不存在\"}");
            }
            saleRecordService.deleteSaleRecord(id);
            return ResponseEntity.ok("{\"message\": \"销售记录删除成功\"}");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                .body("{\"error\": \"删除销售记录失败: " + e.getMessage() + "\"}");
        }
    }
} 